<?php

namespace app\admin\controller\finance;

use app\common\controller\Backend;
use app\admin\model\AuthDepartment;
use fast\Tree;
use app\admin\model\Admin;
use app\common\controller\Api;
use PHPExcel_IOFactory;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Royalty extends Backend
{
    
    /**
     * Wageslist模型对象
     * @var \app\admin\model\Wageslist
     */
    protected $model = null;
    protected $searchFields = 'id,userid,admin.username,admin.mobile,admin.id_number';
    public function _initialize()
    {
        parent::_initialize();
        $this->Infomodel = new \app\admin\model\finance\extract\Info;
        $this->model = new \app\admin\model\Admininfo;
        $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
        $end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
        $this->view->assign("DefaultsTime", $start_time.','.$end_time);
        $this->view->assign("DefaultsDate", date('Y'));
        $this->view->assign("DefaultsDateM", date('m')-1);


        $groupList = collection(AuthDepartment::field('*,parentid as pid')->select())->toArray();
        //$groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        foreach ($result as $k => $v)
        {
            $groupdata[$v['id']] = $v['name'];
        }
        $this->view->assign('groupdata', $groupdata);
      //  $this->view->assign("ticheng", $this->Wagesmodel->getTicheng());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            
            
            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function import(){
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $file = $params['import'];
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;

            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            $row = excelToArrayRoyalty($filePath,$params);
            if (!$row) {
                $this->error(__('No rows were updated'));
            }
            $this->success();
                    
        }
        return $this->view->fetch();
        
    }        
    public function excel(){
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $row = ExcelInfoAll($params);
            if ($row) {
                $title = $params['date'];
                $objWriter = PHPExcel_IOFactory::createWriter($row, 'Excel2007');
                $excelName = "uploads/excel/提成信息-" . $title . ".xlsx";
                $objWriter->save($excelName);
                $this->success('',''.request()->domain().'/'.$excelName.'');
            } else {
                $this->error('暂无信息');
            }
                    
        }
        return $this->view->fetch();
        
    }    
    public function send(){
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $years = $years = explode(',', $params['date']); 
            $userids = '';
            $department = '';
            switch ($params['send_type']) {
                //全部人员
                 case 1:
                    $where = "b.start_time = '".$years[0]."' and b.end_time = '".$years[1]."'";
                     $data = \think\Db::name('admin_info')->alias('a')
                        ->field("b.userid")
                        ->join('finance_extract_info b','a.userid = b.userid')
                        ->where($where)
                        ->select();
                     $userids = !empty($data)?implode('|',array_column($data,'userid')):'';
                    break;
                //指定部门
                 case 2:
                    $data = 1;
                    $department = $params['department'];
                    break; 
                //指定人员
                 case 3:
                    $where = "b.start_time = '".$years[0]."' and b.end_time = '".$years[1]."' and b.`userid` = '".$params['userid']."'";
                     $data = \think\Db::name('admin_info')->alias('a')
                        ->field("b.userid")
                        ->join('finance_extract_info b','a.userid = b.userid')
                        ->where($where)
                        ->find();
                     $userids = !empty($data)?$data['userid']:'';
                    break;
                default:
                    $data = '';
                    break;
            }
              //获取默认值
           if(!empty($data) && (!empty($userids) || !empty($department))){
             $Api = new Api();
               pushMsgText($Api->getConfig($Api->getDefault('Royalty')),'text',['content'=>"".$params['date']."\n版税单已经生成。\n<a href=\"https://oa.fc62.com/index/royalty/lists\">版税信息</a>"] ,$userids,$department);
               $this->success();
            }else{
                $this->error("暂无信息");
            }
        }
        return $this->view->fetch();
        
    }
}
